<template>
  <div class="articleList">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-text="tipText" success-duration="1500">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="加载失败，点击重新加载"
        @load="onLoad"
      >
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
        <article-item v-for="item in list" :key="item.art_id + ''" :title="item.title" :row="item"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import ArticleItem from '../../../components/ArticleItem.vue'
export default {
  components: { ArticleItem },
  props: {
    // 父组件传递的频道id
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      error: false,
      isLoading: false,
      tipText: ''
    }
  },

  created () {

  },

  methods: {
    // 1.进入页面，并且显示list列表组件就会触发
    // 2.加载的数据没有占满一屏，继续加载下一页
    // 3.触底的时候
    async onLoad () {
      // 1.发送请求获取数据
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          with_top: 1,
          timestamp: this.timestamp
        })

        // 用来做测试的代码 随机产生错误
        // if (Math.random() > 0.5) {
        //   console.lg(1111)
        // }
        // 2.保存数据
        this.list.push(...res.results)
        // 更新时间戳
        this.timestamp = res.pre_timestamp
        // 3.让当前这一次的加载状态结束
        this.loading = false
        // 4.数据全部加载完成
        if (!res.results.length) {
          this.finished = true
        }
      } catch (err) {
        // console.dir(err)
        this.error = true
        this.loading = false
      }
    },

    // 触发下拉刷新
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          with_top: 1,
          timestamp: Date.now()
        })
        // 用来测试的代码
        if (Math.random() > 0.5) {
          console.lg(999)
        }
        // console.log(res)
        this.list.unshift(...res.results) // 刷新的新数据需要渲染到列表最前面，所以不用push
        this.isLoading = false
        this.tipText = '刷新成功'
      } catch (err) {
        this.isLoading = false
        this.tipText = '刷新失败，稍后重试'
      }
    }
  }
}
</script>

<style scoped lang='less'>
.articleList {
  height: 80vh;
  overflow-y: scroll;
}
</style>
